package com.xiaoshi.aspect;

import com.google.common.collect.Maps;
import com.xiaoshi.annotation.NoRepeatSubmit;
import com.xiaoshi.exception.PlatformException;
import com.xiaoshi.interfaces.ConstantsRedis;
import com.xiaoshi.utils.GsonUtils;
import com.xiaoshi.utils.ObjectUtils;
import com.xiaoshi.utils.RedisUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


import java.lang.reflect.Field;
import java.util.Map;

@Aspect
public class NoRepeatSubmitAspect {

    private static final Logger logger = LoggerFactory.getLogger(NoRepeatSubmitAspect.class);



    private static final String SUFFIX = "SUFFIX";


    @Autowired
    private static RedisUtils redisUtils;

    /**
     * 横切点
     */
    @Pointcut("@annotation( noRepeatSubmit)")
    public void poinCut(NoRepeatSubmit noRepeatSubmit) {
    }


    /**
     * 接收请求，并记录数据
     */
    @Around(value = "poinCut(noRepeatSubmit)")
    public Object doBefore(ProceedingJoinPoint joinPoint, NoRepeatSubmit noRepeatSubmit) {
        String key = ConstantsRedis.PREFIX.NO_REPEAT_SUBMIT_ASPECT + noRepeatSubmit.location();
        Object[] args = joinPoint.getArgs();
        String name = noRepeatSubmit.name();
        int argIndex = noRepeatSubmit.argIndex();
        String suffix;
        if (ObjectUtils.isEmpty(name)) {
            suffix = String.valueOf(args[argIndex]);
        } else {
            Map<String, Object> keyAndValue = getKeyAndValue(args[argIndex]);
            Object valueObj = keyAndValue.get(name);
            if (valueObj == null) {
                suffix = SUFFIX;
            } else {
                suffix = String.valueOf(valueObj);
            }
        }
        key = key + ":" + suffix;

        logger.info("==================================================");
        for (Object arg : args) {
            logger.info(GsonUtils.toJson(arg));
        }
        logger.info("==================================================");
        int seconds = noRepeatSubmit.seconds();
        logger.info("lock key : " + key);
        if (!isLock(key, seconds)) {
            throw new PlatformException("操作过于频繁，请稍后重试");
        }

        Object proceed=null;

        try {
            proceed = joinPoint.proceed();
            logger.info("@Around：执行目标方法之后...  proceed{}" , proceed);
            return proceed;
        } catch (Throwable throwable) {
            logger.error("运行业务代码出错", throwable);
            throw new RuntimeException(throwable.getMessage());
        } finally {
            /**
             * 是否 代码结束  立即释放锁
             */
            if(noRepeatSubmit.isUnlock())  unLock(key);
        }
    }

    public static Map<String, Object> getKeyAndValue(Object obj) {
        Map<String, Object> map = Maps.newHashMap();
        // 得到类对象
        Class userCla = (Class) obj.getClass();
        /* 得到类中的所有属性集合 */
        Field[] fs = userCla.getDeclaredFields();
        for (int i = 0; i < fs.length; i++) {
            Field f = fs[i];
            // 设置些属性是可以访问的
            f.setAccessible(true);
            Object val = new Object();
            try {
                val = f.get(obj);
                // 得到此属性的值
                // 设置键值
                map.put(f.getName(), val);
            } catch (IllegalArgumentException e) {
                logger.error("【环绕通知】getKeyAndValue IllegalArgumentException", e);
            } catch (IllegalAccessException e) {
                logger.error("【环绕通知】getKeyAndValue IllegalAccessException", e);
            }

        }
        logger.info("扫描结果：" + GsonUtils.toJson(map));
        return map;
    }


    /*@AfterReturning(
            pointcut="execution(* com.hyd.orderMgr.order.controller .*(..)) && args(time, name)",
            returning="returnValue")
    public void access(Date time, Object returnValue, String name) {
        System.out.println("目标方法中的参数String = " + name);
        System.out.println("目标方法中的参数Date = " + time);
        System.out.println("目标方法的返回结果returnValue = " + returnValue);
    }

    //将被AccessArgAdviceTest的access方法匹配
    public String accessAdvice(Date d, String n) {
        System.out.println("方法：accessAdvice");
        return "aa";
    }*/


    public  boolean isLock(String key, int seconds) {
        if (redisUtils.hasKey(key)) {
            return false;
        }
        boolean b = redisUtils.setForObj(key, 1,seconds);
        return true;
    }


    public void unLock(String key) {
        if (redisUtils.hasKey(key)) {
            redisUtils.delForKey(key);
        }

    }


}